<template>
    <div class="chat-container">
        <el-card class="chat-card">
            <template #header>
                <div class="card-header">
                    <span>咨询室</span>
                    <div v-if="connected">
                        <el-tag type="success">已连接</el-tag>
                        <span class="username">用户: {{ userName }}</span>
                    </div>
                    <el-tag v-else type="danger">未连接</el-tag>
                </div>
            </template>

            <div class="chat-messages" ref="messagesContainer">
                <div v-for="(message, index) in messages" :key="index" class="message-item">
                    <div v-if="message.type === 'system'" class="system-message">
                        {{ message.content }}
                    </div>
                    <div v-else class="user-message" :class="{ 'self-message': message.isSelf }">
                        <span class="message-sender">{{ message.sender }}</span>
                        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                        <div class="message-content">{{ message.content }}</div>
                    </div>
                </div>
            </div>

            <div class="chat-input">
                <el-input v-model="inputMessage" placeholder="请输入消息" :disabled="!connected" @keyup.enter="sendMessage">
                    <template #append>
                        <el-button type="primary" :disabled="!connected || !inputMessage" @click="sendMessage">
                            发送
                        </el-button>
                    </template>
                </el-input>
            </div>
        </el-card>

        <div class="connection-controls" v-if="!connected">
            <el-input v-model="userName" placeholder="请输入用户名" />
            <el-button type="primary" class="connect-button" :disabled="!userName" @click="connect">
                加入对话
            </el-button>
        </div>
        <div class="connection-controls" v-else>
            <el-button type="danger" @click="disconnect">离开对话</el-button>
        </div>
    </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { WebSocketUtil } from '../utils/WebSocketUtil';

export default {
    name: 'ChatRoom',
    setup() {
        const messages = ref([]);
        const inputMessage = ref('');
        const userName = ref('');
        const connected = ref(false);
        const messagesContainer = ref(null);

        const wsUrl = 'ws://localhost:9988/WebSocketHandler';
        const websocket = new WebSocketUtil(wsUrl);

        const connect = () => {
            if (!userName.value.trim()) {
                ElMessage.warning('请输入用户名');
                return;
            }

            websocket.connect(userName.value);

            websocket.addOpenHandler(() => {
                connected.value = true;
                addSystemMessage(`欢迎 ${userName.value} 加入对话`);
            });

            websocket.addMessageHandler((message) => {
                addMessage({
                    sender: message.split(':')[0],
                    content: message.split(':')[1]?.trim() || '',
                    timestamp: Date.now(),
                    isSelf: message.startsWith(`${userName.value}:`)
                });
            });

            websocket.addErrorHandler(() => {
                ElMessage.error('WebSocket连接出错');
                disconnect();
            });

            websocket.addCloseHandler(() => {
                connected.value = false;
                addSystemMessage(`用户 ${userName.value} 已离开对话`);
            });
        };

        const disconnect = () => {
            websocket.disconnect();
            connected.value = false;
        };

        const sendMessage = () => {
            if (!inputMessage.value.trim()) return;

            websocket.sendMessage(inputMessage.value);
            inputMessage.value = '';
        };

        const addMessage = (message) => {
            messages.value.push(message);
            scrollToBottom();
        };

        const addSystemMessage = (content) => {
            messages.value.push({
                type: 'system',
                content,
                timestamp: Date.now()
            });
            scrollToBottom();
        };

        const scrollToBottom = () => {
            nextTick(() => {
                if (messagesContainer.value) {
                    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                }
            });
        };

        const formatTime = (timestamp) => {
            const date = new Date(timestamp);
            return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
        };

        onUnmounted(() => {
            disconnect();
        });

        return {
            messages,
            inputMessage,
            userName,
            connected,
            messagesContainer,
            connect,
            disconnect,
            sendMessage,
            formatTime
        };
    }
};
</script>

<style scoped>
.chat-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.chat-card {
    height: 600px;
    display: flex;
    flex-direction: column;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.username {
    margin-left: 10px;
    font-size: 14px;
    color: #666;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin-bottom: 10px;
    height: 500px;
}

.message-item {
    margin-bottom: 12px;
}

.system-message {
    text-align: center;
    color: #999;
    font-size: 12px;
    margin: 5px 0;
}

.user-message {
    background-color: #fff;
    padding: 8px 12px;
    border-radius: 4px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    max-width: 70%;
}

.self-message {
    margin-left: auto;
    background-color: #e1f5fe;
}

.message-sender {
    font-weight: bold;
    font-size: 13px;
    color: #333;
}

.message-time {
    font-size: 11px;
    color: #999;
    margin-left: 8px;
}

.message-content {
    margin-top: 4px;
    word-break: break-word;
}

.chat-input {
    margin-top: 10px;
}

.connection-controls {
    margin-top: 20px;
    display: flex;
    gap: 10px;
}

.connect-button {
    width: 150px;
}
</style>